//
//  NewSearchViewController.swift
//  OnceNectar
//
//  Created by 吴凌 on 2018/7/27.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Alamofire
import PKHUD
import SwiftyJSON
import Networking

struct SearchResultData {
    var information: [ArticleModel] = []
    var video: [VideoModel] = []
    var circle: [CircleModel] = []
    var buy: [GoodsModel] = []
    var user: [UserInfoModel] = []
    var recommend: [SearchRecommendModel] = []
    var type: SearchViewType = .information
    
}

enum SearchType: Int {
    case information
    case video
    case circle
    case buy
    case user
}

class NewSearchViewController: BaseViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, BottomShadow,AddCornerUIRectCorner, UICollectionViewDelegate, UICollectionViewDataSource,SearchHistoryTableViewCellDelegate,SearchUserTableViewCellDelegate {

    @IBOutlet weak var searchView: UIView!
    @IBOutlet weak var resultView: UIView!
    @IBOutlet weak var historyView: UIView!
    @IBOutlet weak var recommendKeyView: UIView!
    @IBOutlet weak var cornerSelectView: CornerSelectionView!
    @IBOutlet weak var historyTableView: UITableView!
    @IBOutlet weak var resultTableView: UITableView!
    @IBOutlet weak var tagView: TagView!
    @IBOutlet weak var recommendView: UICollectionView!

    let searchBar = UISearchBar()
    var historyData:[SearchKeyModel] = []
    var keyData:[SearchKeyModel] = []
    var recommandData:[GoodsModel] = []
    var resultData: SearchResultData = SearchResultData()
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    var page:Int = 0
    var totalPage:Int = 0
    var index = 0
    var emptyView: UIView = UIView()
    let deviceId:String = (UIDevice.current.identifierForVendor?.uuidString)!
    var isChange:Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        searchViewSet()
        fetchKeyList()
        fetchSearchRecordList(parameters: ["deviceId":deviceId])
        fetchSearchRecommandList()
    }
    
    override func setNavigation() {
    }
    
    func setUI() {
        cornerSelectView.show(titles: ["资讯", "视频", "圈子", "购买", "用户"]) {[unowned self] (index) in
            self.index = index
            self.headerRefresh()
        }
        recommendView.backgroundColor = UIColor.clear
        historyTableView.tableFooterView = UIView.init()
        resultTableView.tableFooterView = UIView.init()
        
        historyTableView.register(UINib(nibName: "\(SearchHistoryTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
        resultTableView.register(UINib(nibName: "\(SearchInformationTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "information")
        resultTableView.register(UINib(nibName: "\(SearchUserTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "user")
        recommendView.register(UINib(nibName: "\(ConsultationCollectionViewCell.self)", bundle: nil), forCellWithReuseIdentifier: "cell")
        
        self.resultTableView.addSubview(self.emptyView)
        self.emptyView.frame = self.resultTableView.bounds
        let imageView = UIImageView(image: UIImage(named: "empyt_icon"))
        imageView.center = CGPoint(x: self.emptyView.width / 2, y: self.emptyView.height / 2)
        self.emptyView.addSubview(imageView)
        
        let emptyLabel = UILabel()
        emptyLabel.text = "暂无相关内容"
        self.emptyView.addSubview(emptyLabel)
        emptyLabel.snp.makeConstraints({ (make) in
            make.top.equalTo(imageView.snp.bottom).offset(10)
            make.centerX.equalTo(imageView.snp.centerX)
        })
        self.emptyView.isHidden = true
        
        let headerAction:Selector = #selector(self.headerRefresh)
        self.header.setRefreshingTarget(self, refreshingAction: headerAction)
        self.resultTableView.mj_header = self.header
        
        let footerAction:Selector = #selector(self.footerRefresh)
        self.footer.setRefreshingTarget(self, refreshingAction: footerAction)
        self.resultTableView.mj_footer = self.footer
        
        
        addCornerWithView(aView: self.searchView, aCorners: .allCorners, aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        addCornerWithView(aView: self.resultView, aCorners: .allCorners, aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
    }
    
    func searchViewSet() {
        searchBar.delegate = self
        searchBar.barStyle = .blackTranslucent
        searchBar.backgroundImage = UIImage(named: "searchVC_searchBG")
        searchBar.backgroundColor = UIColor.clear
        searchBar.setSearchFieldBackgroundImage(UIImage(named: "searchVC_searchBG"), for: .normal)
        searchBar.layer.cornerRadius = searchBar.height / 2
        searchBar.layer.masksToBounds = true
        let searchField = searchBar.value(forKey: "searchField") as? UITextField
        searchField?.frame = CGRect.init(x: 0, y: 0, width: ScreenWidth - 100, height: 40)
        if let textField = searchField {
            textField.layer.cornerRadius = searchBar.height / 2
            textField.layer.masksToBounds = true
            textField.backgroundColor = UIColor.clear
            textField.textColor = UIColor.white
            let imageView = UIImageView(image: UIImage(named: "icon_search"))
            imageView.sizeToFit()
            textField.leftView = imageView
        }
        self.navigationItem.titleView = searchBar
    }
    
    // 顶部刷新
    @objc func headerRefresh(){
        print("下拉刷新") // 结束刷新
        page = 0
        self.footerRefresh()
        
    }
    // 底部刷新
    @objc func footerRefresh(){
        print("上拉刷新")
        page += 1
        switch index {
        case 0:
            fetchArticleList(parameters: ["page":page,"pageSize":10,"keyword":searchBar.text!])
        case 1:
            fetchVideoList(parameters: ["page":page,"pageSize":10,"keyword":searchBar.text!])
        case 2:
            fetchCircleList(parameters: ["page":page,"pageSize":10,"keyword":searchBar.text!])
            
        case 3:
            fetchGoodsList(parameters: ["page":page,"pageSize":10,"keyword":searchBar.text!])
            
        case 4:
            fetchUserList(parameters: ["page":page,"pageSize":10,"keyword":searchBar.text!])
            
        default:
            break
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == historyTableView {
            return historyData.count
        }else if tableView == resultTableView{
            switch index {
            case 0:
                return resultData.information.count
            case 1:
                return resultData.video.count
            case 2:
                return resultData.circle.count
            case 3:
                return resultData.buy.count
            case 4:
                return resultData.user.count
            default:
                break
            }
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView == historyTableView {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? SearchHistoryTableViewCell
            cell?.bindData(model: historyData[indexPath.row])
            cell?.delegate = self
            return cell!
        }else if tableView == resultTableView{
            let cell = tableView.dequeueReusableCell(withIdentifier: "information")
            let c = cell as? SearchInformationTableViewCell
            if index == 0 {
                let c = cell as? SearchInformationTableViewCell
                let articleModel = resultData.information[indexPath.row]
                c?.contentLabel.text = articleModel.title!
                let path:String = "\(BaseURL)\(articleModel.coverImgPath!)"
                
                
                let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
                c?.showImageView.sd_setImage(with: url! as URL, completed: nil)
                return cell!
            }else if index == 1 {
                let c = cell as? SearchInformationTableViewCell
                let videoModel = resultData.video[indexPath.row]
                c?.contentLabel.text = videoModel.title!
                let path:String = "\(BaseURL)\(videoModel.coverImgPath!)"
                
                
                let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
                
                c?.showImageView.sd_setImage(with: url! as URL, completed: nil)
                return cell!
            }else if index == 2 {
                let circleModel = resultData.circle[indexPath.row]
                c?.contentLabel.text = circleModel.circleName!
                let path:String = "\(BaseURL)\(circleModel.coverPath!)"
                
                let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
                c?.showImageView.sd_setImage(with: url! as URL, completed: nil)
                return cell!
            }else if index == 3 {
                let c = cell as? SearchInformationTableViewCell
                let buyModel = resultData.buy[indexPath.row]
                c?.contentLabel.text = buyModel.goodsName!
                let path:String = "\(BaseURL)\(buyModel.coverPath!)"
                
                
                let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
                
                c?.showImageView.sd_setImage(with: url! as URL, completed: nil)
                return cell!
            }else if index == 4 {
                let userCell = tableView.dequeueReusableCell(withIdentifier: "user")
                let c = userCell as? SearchUserTableViewCell
                c?.delegate = self
                let userModel = resultData.user[indexPath.row]
                c?.nameLabel.text = userModel.nickname!
                c?.headImgView?.sd_setImage(with: appendUrl(suffix: userModel.headIcon!), completed: nil)
                c?.levelLabel.text = userModel.grade?.gradeCode
                if userModel.matchDegree != "null" {
                    c?.matchLabel.text = userModel.matchDegree
                }
                if userModel.sexy == "男" {
                    c?.sexImgView.image = UIImage(named: "user_gender_male")
                }else{
                    c?.sexImgView.image = UIImage(named: "user_gender_female")
                }
                return userCell!
            }
        }
        return UITableViewCell.init()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if tableView == historyTableView {
            return 44
        }else if tableView == resultTableView{
            if index == 4{
                return 85.5
            }
            return 135
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if tableView == historyTableView {
            let model: SearchKeyModel = historyData[indexPath.row]
            self.searchBar.text = model.name
            self.searchView.isHidden = true
            self.resultView.isHidden = false
            self.headerRefresh()
        }else if tableView == resultTableView{
            if index == 0{
                let articleModel = resultData.information[indexPath.row]
                let vc = ConsultationDetailViewController(nibName: ("\(ConsultationDetailViewController.self)"), bundle: nil, type: HomeVCSelect.news)
                vc.model = articleModel
                self.navigationController?.pushViewController(vc, animated: true)
            }else if(index == 1){
                let articleModel = resultData.video[indexPath.row]
                let vc = VideoDetailViewController(nibName: ("\(VideoDetailViewController.self)"), bundle: nil, type: HomeVCSelect.video)
                vc.model = articleModel
                self.navigationController?.pushViewController(vc, animated: true)
            }
            else if(index == 2){
                let articleModel = resultData.circle[indexPath.row]
                let messageCircleDetailVC = MessageCircleDetailViewController(nibName: "\(MessageCircleDetailViewController.self)", bundle: nil)
                let model: CircleModel? = articleModel
                messageCircleDetailVC.titleLabel(text: (model?.circleName)!, nil)
                messageCircleDetailVC.showRightButtonType = .share
                messageCircleDetailVC.circieId = model?.id
                self.navigationController?.pushViewController(messageCircleDetailVC, animated: true)
            }
            else if(index == 3){
                let articleModel = resultData.buy[indexPath.row]
                let shoppingDetailVC = ShoppingDetailViewController(nibName: "\(ShoppingDetailViewController.self)", bundle: nil)
                shoppingDetailVC.commodityModel = articleModel
                self.navigationController?.pushViewController(shoppingDetailVC, animated: true)
                
            }else if(index == 4){
                let articleModel = resultData.user[indexPath.row]
                let id = articleModel.id
                let messageCirclePersonalCenterVC = PersonInfoViewController(nibName: "\(PersonInfoViewController.self)", bundle: nil)
                messageCirclePersonalCenterVC.userId = id!
                self.navigationController?.pushViewController(messageCirclePersonalCenterVC, animated: true)
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return recommandData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? ConsultationCollectionViewCell
        //        cell?.showImageView.image = UIImage(named: [indexPath.row])
        
        let model = recommandData[indexPath.row]
        if let coverpath = model.coverPath{
            let path:String = "\(BaseURL)\(coverpath)"
            let url = NSURL.init(string: path)
            cell?.showImageView.sd_setImage(with: url! as URL, completed: nil)
        }
        if let name: String = model.goodsName {
            cell?.titleLabel.text = name
        }
        if let type: String = model.label?.name {
            cell?.typeLabel.setTitle(type, for: UIControlState.normal)
        }
        return cell!
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model1:GoodsModel = recommandData[indexPath.item]
        var model: BannerModel = BannerModel()
        model.id = model1.id
        model.type = model1.type
        model.url = model1.contentUrl
        model.coverPath = model1.coverPath
        self.bannerJump(model: model)
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        searchView.isHidden = true
        resultView.isHidden = false
        headerRefresh()
        isChange = true
        fetchSearchRecordList(parameters: ["deviceId":deviceId])
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        searchView.isHidden = false
        resultView.isHidden = true
        if isChange {
            isChange = false
            fetchSearchRecordList(parameters: ["deviceId":deviceId])
        }
    }
    /// 获取搜索关键字数据
    func fetchKeyList() -> Void {
        let requesturl = "\(BaseURL)\(searchKeyUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: nil ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"].array!
                                        
                                        self.keyData.removeAll()
                                        
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            let model = SearchKeyModel(fromDic: dic)
                                            self.keyData.append(model)
                                        }
                                        if(self.keyData.count > 0){
                                            var recommend:[String] = [];
                                            for subject in self.keyData {
                                                recommend.append(subject.name!)
                                            }
                                            self.tagView.showData(titles: recommend, buttnLROffset: 20) {[unowned self] (title) in
                                                self.searchBar.text = title
                                                self.searchView.isHidden = true
                                                self.resultView.isHidden = false
                                                self.headerRefresh()
                                            }
                                        }
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
        }
        
    }
    /// 获取搜索记录数据
    func fetchSearchRecordList(parameters:[String:String]) -> Void {
        let requesturl = "\(BaseURL)\(searchRecordUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"].array!
                                        self.historyData.removeAll()
                                        
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            let model = SearchKeyModel(fromDic: dic)
                                            self.historyData.append(model)
                                        }
                                        if self.historyData.count > 0 {
                                            self.historyView.isHidden = false
                                            self.recommendKeyView.snp.remakeConstraints({ (make) in
                                                make.top.equalToSuperview().offset(self.historyView.height + 20)
                                            })
                                        }else {
                                            self.historyView.isHidden = true
                                            self.recommendKeyView.snp.remakeConstraints({ (make) in
                                                make.top.equalTo(self.searchView.top).offset(10)
                                            })
                                        }
                                        self.historyTableView.reloadData()
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
        }
        
    }
    
    /// 获取搜索记录数据
    func fetchSearchRecommandList() -> Void {
        let requesturl = "\(BaseURL)\(searchRecommendUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: nil ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"].array!
                                        
                                        self.recommandData.removeAll()
                                        
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            let model = SearchRecommendModel(fromDic: dic)
                                            
                                            var model1 = GoodsModel()
                                            model1.coverPath = model.image
                                            model1.id = model.id
                                            model1.goodsName = model.title
                                            model1.label?.name = "为您推荐"
                                            model1.type = model.type
                                            self.recommandData.append(model1)
                                        }
                                        if self.recommandData.count > 0 {
                                            self.recommendView.reloadData()
                                        }else {
                                            self.recommendView.isHidden = true
                                        }
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
        }
        
    }
    
    func delectHistoty(parameters:[String:String]) -> Void{
        let url: URL = appendUrl(suffix: clearHistorySearchUrl)
        Alamofire.request(url, method: .post,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:json["message"].string!)
                                        self.fetchSearchRecordList(parameters: ["deviceId":self.deviceId])
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"请求失败")
                            }
        }
    }
    
    func searchHistoryDedeleteButtonTap(_ cell: SearchHistoryTableViewCell) {
        if self.historyData.count > 0 {
            let indexPath:IndexPath = historyTableView.indexPath(for: cell)!
            let hisId:String = self.historyData[indexPath.row].id!
            self.delectHistoty(parameters: ["deviceId":deviceId,"ids":hisId])
        }
    }

    @IBAction func cleanHistory(_ sender: Any) {
        self.delectHistoty(parameters: ["deviceId":deviceId])
    }
}

extension NewSearchViewController{
    
    
    /// 搜索圈子
    func fetchCircleList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(searchCircleUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page == 1{
                                            self.resultData.circle.removeAll()
                                            self.resultTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.resultTableView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            let model = CircleModel(fromDic: dic)
                                            self.resultData.circle.append(model)
                                        }
                                        if self.totalPage == self.resultData.circle.count{
                                            self.resultTableView.mj_footer.isHidden = true
                                        }
                                        else{
                                            self.resultTableView.mj_footer.isHidden = false
                                        }
                                        if self.resultData.circle.count == 0{
                                            self.emptyView.isHidden = false
                                        }
                                        else
                                        {
                                            self.emptyView.isHidden = true
                                        }
                                        self.resultTableView.reloadData()
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
        }
        
    }
    /// 搜索资讯
    func fetchArticleList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(searchArticleUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page == 1{
                                            self.resultData.information.removeAll()
                                            if self.resultTableView.mj_header != nil{
                                                self.resultTableView.mj_header.endRefreshing()
                                            }
                                        }
                                        else{
                                            if self.resultTableView.mj_footer != nil{
                                                self.resultTableView.mj_footer.endRefreshing()
                                            }
                                            
                                        }
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            let model = ArticleModel(fromDic: dic)
                                            self.resultData.information.append(model)
                                        }
                                        if self.totalPage == self.resultData.information.count{
                                            if self.resultTableView.mj_footer != nil{
                                                self.resultTableView.mj_footer.isHidden = true
                                            }
                                            
                                        }
                                        else{
                                            if self.resultTableView.mj_footer != nil{
                                                self.resultTableView.mj_footer.isHidden = false
                                            }
                                        }
                                        if self.resultData.information.count == 0{
                                            self.emptyView.isHidden = false
                                        }
                                        else
                                        {
                                            self.emptyView.isHidden = true
                                        }
                                        self.resultTableView.reloadData()
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
        }
        
    }
    /// 搜索视频
    func fetchVideoList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(searchVideoUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page == 1{
                                            self.resultData.video.removeAll()
                                            self.resultTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.resultTableView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            let model = VideoModel(fromDic: dic)
                                            self.resultData.video.append(model)
                                        }
                                        if self.totalPage == self.resultData.video.count{
                                            self.resultTableView.mj_footer.isHidden = true
                                        }
                                        else{
                                            self.resultTableView.mj_footer.isHidden = false
                                        }
                                        if self.resultData.video.count == 0{
                                            self.emptyView.isHidden = false
                                        }
                                        else
                                        {
                                            self.emptyView.isHidden = true
                                        }
                                        self.resultTableView.reloadData()
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
        }
        
    }
    /// 搜索购买
    func fetchGoodsList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(searchGoodsUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page == 1{
                                            self.resultData.buy.removeAll()
                                            self.resultTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.resultTableView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            let model = GoodsModel(fromDic: dic)
                                            self.resultData.buy.append(model)
                                        }
                                        if self.totalPage == self.resultData.buy.count{
                                            self.resultTableView.mj_footer.isHidden = true
                                        }
                                        else{
                                            self.resultTableView.mj_footer.isHidden = false
                                        }
                                        if self.resultData.buy.count == 0{
                                            self.emptyView.isHidden = false
                                        }
                                        else
                                        {
                                            self.emptyView.isHidden = true
                                        }
                                        self.resultTableView.reloadData()
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
        }
        
    }
    /// 搜索用户
    func fetchUserList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(searchUserUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page == 1{
                                            self.resultData.user.removeAll()
                                            self.resultTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.resultTableView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            var model = UserInfoModel(fromDic: dic)
                                            
                                            if let dict = dic["grade"]?.dictionary {
                                                model.initGrade(dic: dict)
                                            }
                                            self.resultData.user.append(model)
                                        }
                                        if self.totalPage == self.resultData.user.count{
                                            self.resultTableView.mj_footer.isHidden = true
                                        }
                                        else{
                                            self.resultTableView.mj_footer.isHidden = false
                                        }
                                        self.resultTableView.reloadData()
                                        if self.resultData.user.count == 0{
                                            self.emptyView.isHidden = false
                                        }
                                        else
                                        {
                                            self.emptyView.isHidden = true
                                        }
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
        }
        
    }
    
    /// 关注用户
    func attentionUser(parameters:[String:Any], btn:UIButton) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(attentionUserUrl)"
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        btn.isSelected = true
                                        self.showToast(msg:"关注成功")
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"关注失败")
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    /// 取消关注用户
    func attentionCancelUser(parameters: [String:Any], btn:UIButton) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(attentionCancelUserUrl)"
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        btn.isSelected = false
                                        self.showToast(msg:"取消关注成功")
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                        
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"请求失败")
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
}
